﻿using DeviceCommons.DataHandling;
using DeviceCommons.DeviceMessages.Abstractions;
using DeviceCommons.DeviceMessages.Models.V1;
using DeviceCommons.DeviceMessages.Factories;

namespace DeviceCommons.DeviceMessages.Serialization.V2.Parsers
{
    public class DeviceMessageInfoReadingParser : AbstractMessageParser<IDeviceMessageInfoReading>, IDeviceMessageInfoReadingParser, IContextAwareParser
    {
        private readonly IFastReadingStateFactory _fastFactory;
        private ParsingContext? _context;

        public DeviceMessageInfoReadingParser() : base(new DeviceMessageInfoReading())
        {
            _fastFactory = new FastReadingStateFactory();
        }

        public override IDeviceMessageInfoReading Parser(ReadOnlySpan<byte> bytes)
        {
            // 检查是否有足够的字节来解析时间偏移
            if (bytes.Length < 2)
            {
                // 数据不足，使用传统解析
                return ParseWithTraditionalMethod(bytes);
            }

            // 从上下文中获取设备类型和快速解析标志
            var deviceType = _context?.CurrentDeviceType;
            var enableFastParsing = _context?.EnableFastParsing ?? false;
            
            // 只有在明确启用快速解析且设备类型已注册时才使用快速解析
            if (enableFastParsing && deviceType.HasValue && _fastFactory.SupportsFastParsing(deviceType.Value))
            {
                try
                {
                    return ParseWithFastMethod(bytes, deviceType.Value);
                }
                catch (Exception ex)
                {
                    // 快速解析失败，回退到传统解析
                    Console.WriteLine($"快速解析失败，回退到传统解析: {ex.Message}");
                    return ParseWithTraditionalMethod(bytes);
                }
            }

            // 使用传统解析方法
            return ParseWithTraditionalMethod(bytes);
        }

        /// <summary>
        /// 使用快速方法解析
        /// </summary>
        /// <param name="bytes">字节数组</param>
        /// <param name="deviceType">设备类型</param>
        /// <returns>解析结果</returns>
        private IDeviceMessageInfoReading ParseWithFastMethod(ReadOnlySpan<byte> bytes, byte deviceType)
        {
            // 前2字节是时间偏移
            var timeOffsetBytes = bytes[..2];
            
            // 剩余字节是状态数据
            var stateDataBytes = bytes[2..];
            
            // 使用快速工厂解析状态
            var states = _fastFactory.ParseReadingStates(stateDataBytes, deviceType);
            
            IDeviceMessageInfoReading model = new DeviceMessageInfoReading
            {
                Offset = timeOffsetBytes.ToArray(),
                State = states
            };
            
            Model = model;
            return model;
        }

        /// <summary>
        /// 使用传统方法解析
        /// </summary>
        /// <param name="bytes">字节数组</param>
        /// <returns>解析结果</returns>
        private IDeviceMessageInfoReading ParseWithTraditionalMethod(ReadOnlySpan<byte> bytes)
        {
            IDeviceMessageInfoReading model = new DeviceMessageInfoReading
            {
                Offset = bytes[..2].ToArray(),
                State = DeviceMessageSerializerProvider.InfoReadingStatesV2Par.Parser(bytes[2..])
            };
            Model = model;
            return model;
        }

        public void SetContext(ParsingContext context)
        {
            _context = context;
        }

        public ParsingContext? GetContext()
        {
            return _context;
        }
    }
}
